import boto3
import subprocess   # python 标准库
import os


class eksManage(object):
    def __init__(self,region,cluster_name):
        self.region = region
        self.cluster_name = cluster_name
        
        # 配置AWS环境
        os.environ['AWS_DEFAULT_REGION'] = self.region
    
        # 获取EKS集群认证
        eks = boto3.client('eks')
        cluster = eks.describe_cluster(name=self.cluster_name)
        cluster_cert = cluster['cluster']['certificateAuthority']['data']
        cluster_endpoint = cluster['cluster']['endpoint']
        
        # 更新kubeconfig
        kubeconfig_update_cmd = f"aws eks update-kubeconfig --name {self.cluster_name} --region {self.region}"
        subprocess.run(kubeconfig_update_cmd, shell=True, check=True)
    
    def restartJenkins(self,deployment_name,namespace):
        # 执行rollout restart
        rollout_cmd = f"kubectl rollout restart deployment/{deployment_name} -n {namespace}"
        result = subprocess.run(rollout_cmd, shell=True, capture_output=True, text=True)
        
        if result.returncode == 0:
            print(f"Successfully restarted deployment {deployment_name} in namespace {namespace}")
        else:
            print(f"Error restarting deployment: {result.stderr}")
    
    def deletePipeline(self):
        delete_cmd = "kubectl delete pod --all -n kubesphere-devops-worker"

if __name__ == '__main__':
    doli = eksManage("eu-central-1","doli-k8s")
    doli.restartJenkins("devops-jenkin","kubesphere-devops-system")
    doli.deletePipeline()